using System;
using System.Collections.Generic;
using System.Text;
using Commonplace.Domain;

using MediaWikiEngine;
using MediaWikiEngine.Domain;
using MediaWikiEngine.Command;
using System.IO;
using System.Text.RegularExpressions;

namespace Commonplace.Controller
{
    public class LicenseLoader
    {
        public static List<License> LoadLicenses(WikiConnectionConfig config)
        {
            List<License> licenses = new List<License>();
            
            WikiConnection.WikiEndpoint.BaseAddress = config.BasePath;
            InteractiveCommand cmd = new InteractiveCommand(new WikiConnection(config.Hostname));

            GetPageResult result = cmd.GetPage("MediaWiki", "Licenses");

            if (false == result.Page.Exists)
                return licenses;

            string pattern = @"\**\s*(?<license>.+\|.+)";
            StringReader sr = new StringReader(result.Page.WikiMarkup);
            string line = string.Empty;

            while (null != (line = sr.ReadLine()))
            {
                Match m = Regex.Match(line, pattern);
                if (true == m.Success && true == m.Groups["license"].Success)
                {
                    License license = new License(m.Groups["license"].Value);
                    licenses.Add(license);
                }
            }

            return licenses;
        }

    }
}
